<!-- 模板 -->
<template>
  <div class="record">
    <div class="box">
      <div class="btn">
        <el-form :inline="true" :model="params" size="small" label-width="80px">
          <el-form-item label="测评表:">
            <el-select
              v-model="params.measureTableId"
              placeholder="请选择测评表"
              clearable
              filterable
              @change="search"
            >
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="姓名:">
            <el-input
              v-model="params.userName"
              placeholder="输入姓名"
              clearable
              @clear="search"
            />
          </el-form-item>
          <el-form-item label="代理商:">
            <el-select
              v-model="params.distributorOpenid"
              placeholder="请选择代理商"
              clearable
              filterable
              @change="search"
            >
              <el-option
                v-for="item in options1"
                :key="item.openid"
                :label="item.name"
                :value="item.openid"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="合作商:">
            <el-select
              v-model="params.identificationOpenid"
              placeholder="请选择合作商"
              clearable
              filterable
              @change="search"
            >
              <el-option
                v-for="item in options2"
                :key="item.openid"
                :label="item.name"
                :value="item.openid"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <span style="margin-left: 10px">
            <el-button
              type="primary"
              icon="el-icon-search"
              size="small"
              @click="search"
              >搜索</el-button
            >
            <el-button
              @click="daochu"
              type="success"
              icon="el-icon-download"
              size="small"
              >导 出</el-button
            >
          </span>
        </el-form>
      </div>
      <el-card>
        <el-table :data="tableData" border style="width: 100%">
          <el-table-column label="序号" align="center" type="index">
          </el-table-column>
          <el-table-column
            prop="tableName"
            label="测评表"
            align="center"
            min-width="280"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            prop="userName"
            label="测试人"
            align="center"
            min-width="210"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            prop="phone"
            label="联系方式"
            align="center"
            min-width="150"
          >
          </el-table-column>
          <el-table-column
            prop="sex"
            label="性别"
            align="center"
            min-width="80"
          >
            <template slot-scope="scope">
              {{ scope.row.sex == 1 ? "男" : "女" }}
            </template>
          </el-table-column>
          <el-table-column
            prop="examScore"
            label="得分结果"
            align="center"
            min-width="80"
          >
          </el-table-column>
          <el-table-column
            prop="distributorName"
            label="代理商"
            align="center"
            min-width="220"
          >
            <template slot-scope="scope">
              {{
                scope.row.distributorName == null
                  ? "——"
                  : scope.row.distributorName
              }}
            </template>
          </el-table-column>
          <el-table-column
            prop="agentName"
            label="合作商"
            align="center"
            min-width="220"
          >
            <template slot-scope="scope">
              {{ scope.row.agentName == null ? "——" : scope.row.agentName }}
            </template>
          </el-table-column>
          <el-table-column
            prop="status"
            label="汇总"
            align="center"
            min-width="150"
          >
            <template slot-scope="scope">
              <el-link @click="chakan(scope.row)" v-show="scope.row.status == 1"
                >正常</el-link
              >
              <el-link
                @click="chakan(scope.row)"
                v-show="scope.row.status == 2"
                style="color: #e64242"
                >异常</el-link
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="时间"
            align="center"
            min-width="220"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            prop="content"
            label="备注"
            align="center"
            min-width="280"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            fixed="right"
            min-width="230"
          >
            <template slot-scope="scope">
              <el-button
                @click="handleLookClick(scope.row)"
                type="primary"
                size="small"
                icon="el-icon-edit-outline"
                plain
                >查 看</el-button
              >
              <el-button
                @click="handleDeleteClick(scope.row)"
                type="danger"
                size="small"
                icon="el-icon-delete"
                plain
                >删 除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <pagination
        v-show="newsTotal > 0"
        :total="newsTotal"
        :page.sync="params.pageNum"
        :limit.sync="params.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 查看弹窗 -->
    <el-dialog
      title="查看"
      :visible.sync="dialogVisible"
      width="45%"
      :before-close="handleClose"
    >
      <el-form label-width="100px" :model="form" ref="form">
        <el-row>
          <el-col :span="12">
            <el-form-item label="测评表" prop="tableName">
              <el-input
                v-model="form.tableName"
                style="width: 300px"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="测试人" prop="userName">
              <el-input v-model="form.userName" style="width: 300px"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="phone">
              <el-input v-model="form.phone" style="width: 300px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-input v-model="form.sex" style="width: 300px"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="得分结果" prop="examScore">
              <el-input
                v-model="form.examScore"
                style="width: 300px"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="代理商" prop="agent">
              <el-input v-model="form.agent" style="width: 300px"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="汇总" prop="normalScore">
              <el-input v-model="form.status" style="width: 300px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合作商" prop="partner">
              <el-input v-model="form.partner" style="width: 300px"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="时间">
          <el-date-picker
            v-model="form.createTime"
            type="date"
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <!-- <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="onSubmit">确 定</el-button> -->
      </span>
    </el-dialog>

    <!-- 汇总弹窗 -->
    <el-dialog title="汇总详情" :visible.sync="factorDialogVisible" width="55%">
      <el-table
        :data="tableData1"
        border
        style="width: 100%; height: 700px; overflow: hidden; overflow-y: scroll"
      >
        <el-table-column prop="factorName" label="测量因子名称" align="center">
        </el-table-column>
        <el-table-column prop="factorScore" label="因子分数" align="center">
        </el-table-column>
        <el-table-column prop="proposal" label="建议" align="center">
          <template slot-scope="scope">
            <div v-html="scope.row.proposal"></div>
          </template>
        </el-table-column>
        <el-table-column prop="examExplain" label="解释" align="center">
          <template slot-scope="scope">
            <div v-html="scope.row.examExplain"></div>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="factorDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="factorDialogVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import axios from 'axios'
import { blobValidate } from "@/utils/ruoyi";
import {
  getResultList,
  getResultDet,
  getAgentList,
  getExport,
} from "@/api/finance/index";
import { getWxList, getFactorDsc } from "@/api/partner/index";
import { getList1 } from "@/api/table/table";

export default {
  name: "",
  data() {
    return {
      baseURL: process.env.VUE_APP_BASE_API,
      headers: { Authorization: "Bearer " + getToken() },
      tableData: [],
      tableData1: [],
      params: {
        pageNum: 1,
        pageSize: 10,
      },
      paramsFlag: 0,
      newsTotal: 0,
      options: [],
      options1: [],
      options2: [],
      loading: false,
      dialogVisible: false,
      factorDialogVisible: false,
      form: {},
      xlsxName: '测试记录',
      
    };
  },
  props: [],
  components: {},
  computed: {},
  filters: {},
  methods: {
    //   导出按钮
    daochu() {
      const result = this.options.find(item => item.id === this.params.measureTableId);
      if(result){
        this.xlsxName = result.name + '_测试记录'
      }else{
        this.xlsxName = '测试记录'
      }
      getExport(this.params).then((res) => {
        if (res.code == 200) {
            this.downloadFile(res.msg);
            // window.open('https://celiang.mufengxinli.com/common/download/' + res.msg)
            // 保留之前
            //  window.open('https://9001rzsxy.oss-cn-beijing.aliyuncs.com/9001sxy/other/goods/' + res.msg)
            //  window.open('https://celiang.saipaisikeji.com/home/saipaisi/uploadPath/download/' + res.msg)
        }
      });
    },
    
    // downloadFile 方法，用来下载文件
    downloadFile(fileName) {
      const url = this.baseURL + `/common/download?fileName=${encodeURIComponent( fileName )}&delete=true`;
      axios({
        method: "get",
        url: url,
        responseType: "blob", // 确保响应类型是 Blob（二进制数据）
        headers: this.headers, // 如果需要认证的话
      })
        .then(async (res) => {
          const isLogin = await blobValidate(res.data);
          if (isLogin) {
            // console.log(res);
            const blob = new Blob([res.data]); // 将响应数据转换为 Blob 对象
            const fileName = decodeURI(res.headers["content-disposition"]); // 从响应头获取文件名
            this.saveAs(blob, `${this.xlsxName}.xlsx`); // 使用 file-saver 下载文件
          } else {
            this.printErrMsg(res.data); // 如果不是有效的文件，打印错误信息
          }
        })
        .catch((error) => {
          console.error("下载文件失败：", error);
        });
    },
     // 下载文件的辅助函数
    saveAs(blob, fileName) {
        saveAs(blob, fileName);  // 使用 file-saver 库保存文件
    },
    // 错误消息处理
    async printErrMsg(data) {
      const resText = await data.text();
      const rspObj = JSON.parse(resText);
      const errMsg = rspObj.msg || '下载失败';  // 错误信息
      Message.error(errMsg);  // 显示错误信息
    },

    //   汇总查看按钮
    chakan(row) {
      // console.log(row);
      getFactorDsc(row.id).then((res) => {
        if (res.code == 200) {
          // console.log(res);
          this.tableData1 = res.rows;
          this.factorDialogVisible = true;
        }
      });
    },
    //   查看按钮
    handleLookClick(row) {
      this.form = row;
      if (this.form.status == 1) {
        this.form.status = "正常";
      } else {
        this.form.status = "异常";
      }
      if (this.form.sex == 1) {
        this.form.sex = "男";
      } else {
        this.form.sex = "女";
      }
      this.dialogVisible = true;
    },
    handleClose() {
      this.dialogVisible = false;
      this.getList();
    },
    // 代理商
    getAgentList() {
      getAgentList().then((res) => {
        if (res.code == 200) {
          this.options1 = res.rows;
        }
      });
    },
    // 团体合作商
    getUserList() {
      getWxList().then((res) => {
        let a = res.rows;
        for (let i = 0; i < a.length; i++) {
          if (a[i].agentType == 3) {
            this.options2.push(a[i]);
          }
        }
        // console.log(this.options2);
      });
    },
    // 搜索
    search() {
      this.$set(this.params, "pageNum", 1);
      this.paramsFlag = 0;
      this.getList();
    },
    //   获取测量表
    getTableList() {
      getList1().then((res) => {
        if (res.code == 200) {
          this.options = res.rows;
          // console.log(this.options);
        }
      });
    },
    handleDeleteClick(row) {
      const id = row.id;
      // console.log(id)
      this.$confirm("是否确认删除?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return getResultDet(id);
        })
        .then(() => {
          this.getList();
          this.$message.success("删除成功");
        })
        .catch(function () {});
    },
    // 获取所有
    getList() {
      this.loading = true;
      getResultList(this.params).then((res) => {
        this.tableData = res.rows;
        this.newsTotal = res.total;
        this.loading = false;
      });
    },
  },
  created() {
    this.getUserList();
    this.getList();
    this.getTableList();
    this.getAgentList();
  },
  mounted() {},
};
</script>

<style rel="stylesheet/scss" lang="scss">
.box {
  margin: 10px;
  .btn {
    margin-top: 20px;
  }
}
.el-table::before {
  z-index: inherit !important;
}
</style>
